<?php
class Development_Plugin_RSS_Reader extends appRain_Base_Objects{

    private $xml = "";
    
    public function Parse($isFullobj=false)
    {
        $this->xml = $this->fetchContent();
        return ($isFullobj==='text') ? $this->xml : $this->runPurser($isFullobj);
    }

    public function runPurser($isFullobj=false)
    {   
        $xml =  simplexml_load_string(utf8_encode($this->xml2normalize($this->xml)));
        if($isFullobj == true){
            return $xml;
        }
        else {
            $data = Array();
            if(!empty($xml->channel->item)){
            foreach($xml->channel->item as $post) {
                $data[] = $post;
            }}
            return $data;
        }
    }

    public function xml2normalize($s = "")
    {
        return  preg_replace('/&[^; ]{0,6}.?/e', "((substr('\\0',-1) == ';') ? '\\0' : '&amp;'.substr('\\0',1))", $s);
    }
    public function fetchContent()
    {
       if(!App::Module("Cache")->Exists($this->getKey())){
           $data = App::Module('Remote')
                ->addField('url',$this->getFeedUri())
                ->execute();
            App::Module("Cache")->Write($this->getKey(),$data);
       }

       $str = App::Module("Cache")->Read($this->getKey());
       $a = strpos($str,'<');
       $str = substr($str,$a,strlen($str));
      return $str;
    }

    public function getKey()
    {//pre(App::Helper('Utility')->text2normalize($this->getFeedUri()) . '-' . date('d-m-Y'));
        return App::Helper('Utility')->text2normalize($this->getFeedUri()) . '-' . date('d-m-Y');
    }
}
